/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package persistence;

import entityBeans.Habitat;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entityBeans.Eventelement;
import java.util.ArrayList;
import java.util.List;
import entityBeans.Localityelement;
import persistence.exceptions.NonexistentEntityException;

/**
 *
 * @author allankv
 */
public class HabitatJpaController {

    public HabitatJpaController() {
        emf = Persistence.createEntityManagerFactory("bdd-javaPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public Habitat save(Habitat habitat) {
        Habitat aux = findHabitat(habitat.getHabitat());
        if(aux==null)
            return create(habitat);
        else
            return aux;
    }

    public Habitat create(Habitat habitat) {
        Habitat r = null;
        if (habitat.getEventelementList() == null) {
            habitat.setEventelementList(new ArrayList<Eventelement>());
        }
        if (habitat.getLocalityelementList() == null) {
            habitat.setLocalityelementList(new ArrayList<Localityelement>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Eventelement> attachedEventelementList = new ArrayList<Eventelement>();
            for (Eventelement eventelementListEventelementToAttach : habitat.getEventelementList()) {
                eventelementListEventelementToAttach = em.getReference(eventelementListEventelementToAttach.getClass(), eventelementListEventelementToAttach.getIdeventelement());
                attachedEventelementList.add(eventelementListEventelementToAttach);
            }
            habitat.setEventelementList(attachedEventelementList);
            List<Localityelement> attachedLocalityelementList = new ArrayList<Localityelement>();
            for (Localityelement localityelementListLocalityelementToAttach : habitat.getLocalityelementList()) {
                localityelementListLocalityelementToAttach = em.getReference(localityelementListLocalityelementToAttach.getClass(), localityelementListLocalityelementToAttach.getIdlocalityelement());
                attachedLocalityelementList.add(localityelementListLocalityelementToAttach);
            }
            habitat.setLocalityelementList(attachedLocalityelementList);
            r = em.merge(habitat);
            for (Eventelement eventelementListEventelement : habitat.getEventelementList()) {
                Habitat oldHabitatOfEventelementListEventelement = eventelementListEventelement.getHabitat();
                eventelementListEventelement.setHabitat(habitat);
                eventelementListEventelement = em.merge(eventelementListEventelement);
                if (oldHabitatOfEventelementListEventelement != null) {
                    oldHabitatOfEventelementListEventelement.getEventelementList().remove(eventelementListEventelement);
                    oldHabitatOfEventelementListEventelement = em.merge(oldHabitatOfEventelementListEventelement);
                }
            }
            for (Localityelement localityelementListLocalityelement : habitat.getLocalityelementList()) {
                Habitat oldHabitatOfLocalityelementListLocalityelement = localityelementListLocalityelement.getHabitat();
                localityelementListLocalityelement.setHabitat(habitat);
                localityelementListLocalityelement = em.merge(localityelementListLocalityelement);
                if (oldHabitatOfLocalityelementListLocalityelement != null) {
                    oldHabitatOfLocalityelementListLocalityelement.getLocalityelementList().remove(localityelementListLocalityelement);
                    oldHabitatOfLocalityelementListLocalityelement = em.merge(oldHabitatOfLocalityelementListLocalityelement);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
        return r;
    }

    public void edit(Habitat habitat) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Habitat persistentHabitat = em.find(Habitat.class, habitat.getIdhabitat());
            List<Eventelement> eventelementListOld = persistentHabitat.getEventelementList();
            List<Eventelement> eventelementListNew = habitat.getEventelementList();
            List<Localityelement> localityelementListOld = persistentHabitat.getLocalityelementList();
            List<Localityelement> localityelementListNew = habitat.getLocalityelementList();
            List<Eventelement> attachedEventelementListNew = new ArrayList<Eventelement>();
            for (Eventelement eventelementListNewEventelementToAttach : eventelementListNew) {
                eventelementListNewEventelementToAttach = em.getReference(eventelementListNewEventelementToAttach.getClass(), eventelementListNewEventelementToAttach.getIdeventelement());
                attachedEventelementListNew.add(eventelementListNewEventelementToAttach);
            }
            eventelementListNew = attachedEventelementListNew;
            habitat.setEventelementList(eventelementListNew);
            List<Localityelement> attachedLocalityelementListNew = new ArrayList<Localityelement>();
            for (Localityelement localityelementListNewLocalityelementToAttach : localityelementListNew) {
                localityelementListNewLocalityelementToAttach = em.getReference(localityelementListNewLocalityelementToAttach.getClass(), localityelementListNewLocalityelementToAttach.getIdlocalityelement());
                attachedLocalityelementListNew.add(localityelementListNewLocalityelementToAttach);
            }
            localityelementListNew = attachedLocalityelementListNew;
            habitat.setLocalityelementList(localityelementListNew);
            habitat = em.merge(habitat);
            for (Eventelement eventelementListOldEventelement : eventelementListOld) {
                if (!eventelementListNew.contains(eventelementListOldEventelement)) {
                    eventelementListOldEventelement.setHabitat(null);
                    eventelementListOldEventelement = em.merge(eventelementListOldEventelement);
                }
            }
            for (Eventelement eventelementListNewEventelement : eventelementListNew) {
                if (!eventelementListOld.contains(eventelementListNewEventelement)) {
                    Habitat oldHabitatOfEventelementListNewEventelement = eventelementListNewEventelement.getHabitat();
                    eventelementListNewEventelement.setHabitat(habitat);
                    eventelementListNewEventelement = em.merge(eventelementListNewEventelement);
                    if (oldHabitatOfEventelementListNewEventelement != null && !oldHabitatOfEventelementListNewEventelement.equals(habitat)) {
                        oldHabitatOfEventelementListNewEventelement.getEventelementList().remove(eventelementListNewEventelement);
                        oldHabitatOfEventelementListNewEventelement = em.merge(oldHabitatOfEventelementListNewEventelement);
                    }
                }
            }
            for (Localityelement localityelementListOldLocalityelement : localityelementListOld) {
                if (!localityelementListNew.contains(localityelementListOldLocalityelement)) {
                    localityelementListOldLocalityelement.setHabitat(null);
                    localityelementListOldLocalityelement = em.merge(localityelementListOldLocalityelement);
                }
            }
            for (Localityelement localityelementListNewLocalityelement : localityelementListNew) {
                if (!localityelementListOld.contains(localityelementListNewLocalityelement)) {
                    Habitat oldHabitatOfLocalityelementListNewLocalityelement = localityelementListNewLocalityelement.getHabitat();
                    localityelementListNewLocalityelement.setHabitat(habitat);
                    localityelementListNewLocalityelement = em.merge(localityelementListNewLocalityelement);
                    if (oldHabitatOfLocalityelementListNewLocalityelement != null && !oldHabitatOfLocalityelementListNewLocalityelement.equals(habitat)) {
                        oldHabitatOfLocalityelementListNewLocalityelement.getLocalityelementList().remove(localityelementListNewLocalityelement);
                        oldHabitatOfLocalityelementListNewLocalityelement = em.merge(oldHabitatOfLocalityelementListNewLocalityelement);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = habitat.getIdhabitat();
                if (findHabitat(id) == null) {
                    throw new NonexistentEntityException("The habitat with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Habitat habitat;
            try {
                habitat = em.getReference(Habitat.class, id);
                habitat.getIdhabitat();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The habitat with id " + id + " no longer exists.", enfe);
            }
            List<Eventelement> eventelementList = habitat.getEventelementList();
            for (Eventelement eventelementListEventelement : eventelementList) {
                eventelementListEventelement.setHabitat(null);
                eventelementListEventelement = em.merge(eventelementListEventelement);
            }
            List<Localityelement> localityelementList = habitat.getLocalityelementList();
            for (Localityelement localityelementListLocalityelement : localityelementList) {
                localityelementListLocalityelement.setHabitat(null);
                localityelementListLocalityelement = em.merge(localityelementListLocalityelement);
            }
            em.remove(habitat);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Habitat> findHabitatEntities() {
        return findHabitatEntities(true, -1, -1);
    }

    public List<Habitat> findHabitatEntities(int maxResults, int firstResult) {
        return findHabitatEntities(false, maxResults, firstResult);
    }

    private List<Habitat> findHabitatEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Habitat.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }
    public Habitat findHabitat(String q) {
        Query query= getEntityManager().createNamedQuery("Habitat.findByHabitat");
        query.setParameter("habitat",q);

        return query.getResultList().isEmpty()?null:(Habitat)query.getResultList().get(0);
    }

    public Habitat findHabitat(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Habitat.class, id);
        } finally {
            em.close();
        }
    }

    public int getHabitatCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Habitat> rt = cq.from(Habitat.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
